package com.prig.base.shiro;

import com.prig.base.entity.Admin;
import com.prig.base.entity.Permission;
import com.prig.base.entity.Role;
import com.prig.base.service.AdminService;
import com.prig.base.service.PermissionService;
import com.prig.base.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class UserRealm extends AuthorizingRealm {

    private AdminService adminService;
    private RoleService roleService;
    private PermissionService permissionService;
    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }
    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
    @Autowired
    public void setPermissionService(PermissionService permissionService) {
        this.permissionService = permissionService;
    }


    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        //设置用于匹配密码的CredentialsMatcher
        HashedCredentialsMatcher hashcredentialsMatcher = new HashedCredentialsMatcher();
        hashcredentialsMatcher.setHashAlgorithmName("MD5");
        hashcredentialsMatcher.setHashIterations(2);
        hashcredentialsMatcher.setStoredCredentialsHexEncoded(true);
        super.setCredentialsMatcher(hashcredentialsMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            String name = principalCollection.getPrimaryPrincipal().toString();
            Admin admin = adminService.getAdmin(new Admin(name));
            List<Role> roles = roleService.getRoles(admin.getId());
            List<Permission> permissions = permissionService.getPermissions(
                    String.join(",", roles.stream().map(x-> Long.toString(x.getId())).collect(Collectors.toSet()) ));
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setRoles(roles.stream().map(Role::getRoleName).collect(Collectors.toSet()));
            info.setStringPermissions(permissions.stream().map(Permission::getUrl).collect(Collectors.toSet()));
            return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken)authenticationToken;
        Admin admin = adminService.getAdmin(new Admin(userToken.getUsername()));
        if (admin == null){
            //当用户不存在的时候，抛出此异常
            throw new UnknownAccountException("找不到用户(" + userToken.getUsername() + ")的账号信息");
        }
//        Admin adminpass = new Admin(userToken.getUsername(),userToken.getPassword().toString());
        return new SimpleAuthenticationInfo(userToken.getUsername(),admin.getPassword(),
                ByteSource.Util.bytes(userToken.getUsername()),getName());
    }
}
